<?php
/**
 * Created by PhpStorm.
 * Author: DaXiong
 * Date: 2018/10/22
 * Time: 9:03
 */

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\User;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Mews\Captcha\Facades\Captcha;

/**
 * 登录相关
 * Class CateController
 * @package App\Http\Controllers
 */
class AuthController extends Controller {

    /**
     * 登录
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function login(Request $request){
        $data = $request->only('username', 'password', 'captcha', 'captchaKey');

        if(!isset($data['username']) || strlen($data['username'])>10){
            return $this->returnJson(1, '拒绝你的非法登录请求!');
        }


        $check = Captcha::check_api($data['captcha'], $data['captchaKey']);
        if (!$check) {
            return $this->returnJson(1, '验证码错误');
        }
        $user = User::where('openid',$data['username'])->first();
        if(!$user){
            //用户不存在
            return $this->returnJson(1, '该用户不存在，请联系管理员创建！');
        }
        try {
            $client = new Client();
            $url = request()->root() . '/oauth/token';
            $params = array_merge(config('passport.proxy'), [
                'username' => $data['username'],
                'password' => $data['password'],
                'provider' => 'admin'
            ]);

            $response = $client->request('POST', $url, ['form_params' => $params]);
            $token_info = json_decode($response->getBody()->getContents());
            return $this->returnJson(0,'',$token_info);
        } catch (\Exception $e) {
            return $this->returnJson(1, '登录失败');
        }
    }

    /**
     * 创建管理员账号
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * Author: DaXiong
     */
    public function register(Request $request){
        $data = $request->all();
        $user = User::where('openid',$data['openid'])->first();
        if($user){
            //用户已存在
            return $this->returnJson(1, '该用户已存在！');
        }else{
            try {
                //不存在创建新用户
                User::create([
                    'openid' => $data['openid'],
                    'password' => bcrypt($data['password']),
                    'is_admin' => 1,
                ]);
                return $this->returnJson(1, '成功创建新用户：'.$data['openid']);
            } catch (RequestException $exception) {
                return $this->returnJson(1, '创建新用户失败！');
            }
        }
    }

    /**
     * 更新管理员密码
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * Author: DaXiong
     */
    public function changePassword(Request $request){
        $data = $request->all();
        $user = User::where('openid',$data['openid'])->first();
        if(!$user){
            //用户不存在
            return $this->returnJson(1, '该用户不存在，请联系管理员创建！');
        }
        try {
            $user->update(['password'=>bcrypt($data['password'])]);
            return $this->returnJson(1, $data['openid'].' 更新密码成功');
        } catch (RequestException $exception) {
            return $this->returnJson(1, '更新密码失败！');
        }
    }

    /**
     * 刷新token
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function refresh(Request $request){
        try {
            $refreshToken = $request->get('refresh_token','');
            if(empty($refreshToken)){
                return $this->returnJson(1, '参数错误');
            }
            $client = new Client();
            $url = request()->root() . '/oauth/token';
            $params = array_merge(config('passport.refresh'), [
                'refresh_token' => $refreshToken,
            ]);
            $response = $client->request('POST', $url, ['form_params' => $params]);
            $token_info = json_decode($response->getBody()->getContents());
            return $this->returnJson(0,'',$token_info);
        } catch (RequestException $exception) {
            return $this->returnJson(1, '刷新失败');
        }
        //
        //
    }

    /**
     * 退出登录
     * @return \Illuminate\Http\JsonResponse|string
     */
    public function logout()
    {
        if (auth()->guard('api')->check()) {
            auth()->guard('api')->user()->token()->delete();
            return $this->returnJson(0,'登出成功,页面即将跳转...');
        }
        return '';
    }

    /**
     * 获取 验证码图片
     * @return \Illuminate\Http\JsonResponse
     * Author: DaXiong
     */
    public function captcha(){
//        $captcha = Captcha::create('default', true);
//        return $this->returnJson(0,'',$captcha);
        try {
            $captcha = Captcha::create('default', true);
            return $this->returnJson(0,'',$captcha);
        } catch (\Exception $e) {
            return $this->returnJson(1, '网络超时，请刷新再试');
        }
    }

}
